package com.valveinspectionsys.rushrepair.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;

import android.provider.Settings;
import android.view.Menu;
import android.widget.Toast;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKLocationManager;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.OverlayItem;
import com.valveinspectionsys.MapApplication;
import com.valveinspectionsys.R;
import com.valveinspectionsys.dbhelp.XmlNameHelper;
import com.valveinspectionsys.gridview.GridViewDao;
import com.valveinspectionsys.povo.DeviceVo;
import com.valveinspectionsys.util.BaiDuGpsUtil;
import com.valveinspectionsys.util.SharedPreferenceUtil;

/**
 * 通过地图生成强修改信息
 * @author King
 *
 */
public class RushRepairMapActivity extends MapActivity {
    // 定位图层
    public MyLocationOverlay mLocationOverlay = null;

    public MapView mMapView = null; // 地图View
  
    public LocationListener mLocationListener = null;// create时注册此listener，Destroy时需要Remove


    public MKLocationManager locationMan = null;// 定位管理

    public static final int ITEM0 = Menu.FIRST;// 系统值

    public String locationtype = "network";

    private final static int DIALOG = 1;
    public boolean isinit = true;

    

    public boolean isSerch = false;

    public boolean isStop = true;

    public OverItemT itme;

    public int n = 0;

    public boolean isOk = false;

 
    public List<DeviceVo> list;

    public int AroundNumber = 0;
    
    public GridViewDao  dao;

    @Override
    protected void onCreate(Bundle bundle) {

	super.onCreate(bundle);
	setContentView(R.layout.rush_repair_map);
	SharedPreferenceUtil sp = new SharedPreferenceUtil(this);
	
	mMapView = (MapView) findViewById(R.id.bmapView);

	
	 dao = new GridViewDao(this,sp.getValue(XmlNameHelper.SqliteName));
	list = dao.queryDeviceList(null);
	
	init();
    }

    @Override
    protected boolean isRouteDisplayed() {

	return false;
    }

    @Override
    protected void onPause() {
	MapApplication app = (MapApplication) this.getApplication();
	app.mBMapMan.getLocationManager().removeUpdates(mLocationListener);
	mLocationOverlay.disableMyLocation();
	mLocationOverlay.disableCompass(); // 闭指南针
	app.mBMapMan.stop();
	super.onPause();
    }

    @Override
    protected void onResume() {
	MapApplication app = (MapApplication) this.getApplication();
	locationInit();
	app.mBMapMan.getLocationManager().requestLocationUpdates(mLocationListener);
	app.mBMapMan.getLocationManager().setNotifyInternal(1, 10);
	mLocationOverlay.enableMyLocation();
	mLocationOverlay.enableCompass(); // 打开指南针
	app.mBMapMan.start();
	super.onResume();
    }

    /**
     * 初始化控件并设置参数
     */
    public void init() {
	
	
	MapApplication app = (MapApplication) this.getApplication();
	mLocationListener = new MyLocationListen();

	if (app.mBMapMan == null) {
	    app.mBMapMan = new BMapManager(getApplication());
	    app.mBMapMan.init(app.mStrKey, new MapApplication.MyGeneralListener());
	}
	app.mBMapMan.start();
	// 初始化地图Activity
	super.initMapActivity(app.mBMapMan);
	// 得到地图层的控制权，可以用它控制和驱动平移和缩放
	MapController bMapController = mMapView.getController();
	// 设置地图ZOOM级别
	if (bMapController != null) {
	    bMapController.setZoom(18);
	}

	mMapView.setBuiltInZoomControls(true);
	// 设置在缩放动画过程中也显示overlay,默认为不绘制
	mMapView.setDrawOverlayWhenZooming(true);
	// 设置定位中心
	
	mMapView.invalidate();
	// 添加定位图层
	mLocationOverlay = new MyLocationOverlay(this, mMapView) {

	    @Override
	    protected void drawMyLocation(Canvas canvas, MapView mapView, Location lastFix, GeoPoint myLocation, long when) {

		super.drawMyLocation(canvas, mapView, lastFix, myLocation, when);
	    }

	};

	mMapView.getOverlays().add(mLocationOverlay);

	
	locationMan = app.mBMapMan.getLocationManager();
	

    }

   

    /**
     * 定位监听器
     * 
     * @author king
     * 
     */
    public class MyLocationListen implements LocationListener {

	@Override
	public void onLocationChanged(Location location) {
	    if (location == null) {
		return;
	    }

	   
		    mMapView.getOverlays().clear();
		
		
		GeoPoint pt = new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));
		// mMapView.getOverlays().remove(mMapView.getOverlays().size() -
		// 1 - AroundNumber);
		
		AroundNumber = 0;
		SerchAroundWater(location);
		Drawable marker = getResources().getDrawable(R.drawable.location); // 得到需要标在地图上的资源
		
	       OverItemS	itme = new OverItemS(pt, marker, RushRepairMapActivity.this, "这是你的位置");

		mMapView.getOverlays().add(itme); // 添加ItemizedOverlay实例到mMapView
		mMapView.getController().animateTo(pt);
		mMapView.invalidate();

	    	  

	}
    }

    /**
     * 定位初始化
     */
    public void locationInit() {
	if (locationtype.equals("gps")) {
	    locationMan.enableProvider(MKLocationManager.MK_GPS_PROVIDER);
	    locationMan.disableProvider(MKLocationManager.MK_NETWORK_PROVIDER);
	} else if (locationtype.equals("network")) {
	    locationMan.enableProvider(MKLocationManager.MK_NETWORK_PROVIDER);
	    locationMan.disableProvider(MKLocationManager.MK_GPS_PROVIDER);
	}

    }

  
    /**
     * 点击事件标注
     * 
     * @author king
     * 
     */
    public class OverItemT extends ItemizedOverlay<OverlayItem> {

	private GeoPoint geopoint;
	private List<OverlayItem> GeoList = new ArrayList<OverlayItem>();
	private Context mContext;
	private Dialog  dialog;
	private DeviceVo  device;

	public OverItemT(GeoPoint geopoint, Drawable marker, Context context, DeviceVo device) {
	    super(boundCenterBottom(marker));
	    this.mContext = context;
	    this.geopoint = geopoint;
	    this.device=device;
	   
	    GeoList.add(new OverlayItem(geopoint, "p1", ""));
	    populate();

	}

	@Override
	protected OverlayItem createItem(int arg0) {
	    // TODO Auto-generated method stub
	    return GeoList.get(arg0);
	}

	@Override
	public int size() {
	    // TODO Auto-generated method stub
	    return GeoList.size();
	}

	@Override
	// 处理当点击事件
	protected boolean onTap(int i) {
	    AlertDialog.Builder   builder=new  AlertDialog.Builder(mContext);
	    builder.setTitle("提示");
	   
	    StringBuffer sb=new StringBuffer("设备信息\r\n  设备类型:"+device.getDeviceType()+"\r\n");
	    sb.append("设备地址:"+device.getDeviceAdds()+"\r\n");
	    sb.append("公称口径:"+device.getDeviceCaliber()+"\r\n");
	    sb.append("公称压力:"+device.getDevicePressure()+"\r\n");
	    sb.append("生产商"+device.getProducers()+"\r\n");
	    sb.append("安装日期:"+device.getInstallationDate()+"\r\n");
	    sb.append("确定生成抢修单！");
	    builder.setMessage(sb.toString());
	    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
	        
	        @Override
	        public void onClick(DialogInterface dialog, int which) {
	    	        Intent  intent=new Intent(RushRepairMapActivity.this, RushRepairNoRfidActivity.class);
	    	        intent.putExtra("deviceid", device.getDeviceId());
	    	        startActivity(intent);
	    	        finish();
	    	      dialog.dismiss();
	        }
	    });
	    builder.setNegativeButton("取消", null);
	    dialog=builder.create();
	    dialog.show();
	    return true;
	}
    }

    /**
     * 点击事件标注
     * 
     * @author king
     * 
     */
    public class OverItemS extends ItemizedOverlay<OverlayItem> {

	private GeoPoint geopoint;
	private List<OverlayItem> GeoList = new ArrayList<OverlayItem>();
	private Context mContext;
	

	public OverItemS(GeoPoint geopoint, Drawable marker, Context context, String message) {
	    super(boundCenterBottom(marker));
	    this.mContext = context;
	    this.geopoint = geopoint;
	   
	    GeoList.add(new OverlayItem(geopoint, "p1", message));
	    populate();

	}

	@Override
	protected OverlayItem createItem(int arg0) {
	    // TODO Auto-generated method stub
	    return GeoList.get(arg0);
	}

	@Override
	public int size() {
	    // TODO Auto-generated method stub
	    return GeoList.size();
	}

	@Override
	// 处理当点击事件
	protected boolean onTap(int i) {
	//    Toast.makeText(this.mContext, GeoList.get(i).getSnippet(), Toast.LENGTH_SHORT).show();
	    return true;
	}
    }
    
    /**
     * 判断GPS是否存在或开启
     */
    public boolean openGPSSettings() {
	LocationManager alm = (LocationManager) getSystemService(this.LOCATION_SERVICE);

	if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {

	    return true;
	}
	Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
	Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
	startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
	return false;
    }

  

 

    /**
     * 查询前位置周围1000米内的水表
     * 
     * @param location
     */
    public void SerchAroundWater(Location location) {
	Double d = 0.0;

	for (int i = 0; i < list.size(); i++) {
	    DeviceVo water = list.get(i);
	    d = BaiDuGpsUtil.GetShortDistance(location.getLongitude(), location.getLatitude(), water.getLongitude(), water.getLatitude());
	    if (d <= 1000) {
		GeoPoint pt = new GeoPoint((int) (water.getLatitude() * 1E6), (int) (water.getLongitude() * 1E6));
		
		    Drawable marker = getResources().getDrawable(R.drawable.is_copywater); // 得到需要标在地图上的资源
		    itme = new OverItemT(pt, marker, RushRepairMapActivity.this, water);
		    mMapView.getOverlays().add(itme);
		
		AroundNumber++;
	    }
	}
    }

    @Override
    protected void onDestroy() {
	dao.close();
	super.onDestroy();
    }

}
